/*
 * Copyright 2010 Yannick Stucki (yannickstucki.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yannickstucki.android.musicqueue.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.TreeSet;

import com.yannickstucki.android.musicqueue.communication.OnSongsUpdatedListener;

/**
 * Class that obtains all the songs information.
 * 
 * @author Yannick Stucki (yannickstucki@gmail.com)
 * 
 */
public class SongUpdate {

  /**
   * A cursor to all the songs.
   */
  private ISongCursor songCursorAll;

  /**
   * A cursor to the starred songs.
   */
  private ISongCursor songCursorStarred;

  /**
   * A handler to notify that the update has occurred.
   */
  private OnSongsUpdatedListener handler;

  /**
   * The constructor sets the references.
   */
  public SongUpdate(ISongCursor songCursorAll, ISongCursor songCursorStarred,
      OnSongsUpdatedListener handler) {
    this.songCursorAll = songCursorAll;
    this.songCursorStarred = songCursorStarred;
    this.handler = handler;
  }

  /**
   * Reads the cursors and posts the results to the handler.
   */
  public SongUpdateResult update() {
    ArrayList<Song> starredSongsList = new ArrayList<Song>();
    if (songCursorStarred.query()) {
      do {
        starredSongsList.add(songCursorStarred.getSong());
      } while (songCursorStarred.moveToNext());
    }
    int starredLength = starredSongsList.size();

    ArrayList<Song> allSongs = new ArrayList<Song>();
    if (songCursorAll.query()) {
      do {
        allSongs.add(songCursorAll.getSong());
      } while (songCursorAll.moveToNext());
    }
    int allLength = allSongs.size();

    Collections.sort(allSongs);

    // Starred songs
    TreeSet<Song> starredSongs = new TreeSet<Song>();
    TreeSet<Song> starredSongsTemp = new TreeSet<Song>();

    for (int i = 0; i < starredLength; i++) {
      starredSongsTemp.add(starredSongsList.get(i));
    }

    if (starredSongsTemp.size() > 0) {
      for (int i = 0; i < allLength; i++) {
        if (starredSongsTemp.contains(allSongs.get(i))) {
          allSongs.get(i).starred = true;
          // Add the songs to the "real" starred songs
          starredSongs.add(allSongs.get(i));
        }
      }
    }

    return new SongUpdateResult(allSongs, starredSongs, handler);
  }
}
